<template>
  <div class="parameter-container">
    <a-card :bordered="false" class="main-card">
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">参数管理</h1>
          <span class="page-description">管理商品参数和规格</span>
        </div>
      </div>
      <div class="parameter-content">
        <!-- 左侧参数项列表 -->
        <div class="parameter-list">
          <div class="list-header">
            <div class="header-content">
              <div class="header-left">
                <span class="header-title">参数项列表</span>
                <span class="header-count">共 {{ parameterItems.length }} 项</span>
              </div>
              <a-button type="primary" @click="showAddModal" class="add-button">
                <template #icon><plus-outlined /></template>
                添加参数
              </a-button>
            </div>
          </div>
          <a-divider style="margin: 12px 0" />
          <a-list
            :data-source="parameterItems"
            :loading="loading"
            item-layout="horizontal"
            class="custom-list"
          >
            <template #renderItem="{ item }">
              <a-list-item
                :class="{ 'selected-item': selectedItem?.id === item.id }"
                @click="handleSelectItem(item)"
              >
                <a-list-item-meta>
                  <template #title>
                    <div class="item-title">
                      <span class="item-name">{{ item.name }}</span>
                      <span class="item-tags">
                        <a-tag :color="item.type === 0 ? 'blue' : 'green'" class="type-tag">
                          {{ item.type === 0 ? '单选' : '多选' }}
                        </a-tag>
                        <a-tag :color="item.isRequired === 1 ? 'red' : 'default'" class="required-tag">
                          {{ item.isRequired === 1 ? '必选' : '可选' }}
                        </a-tag>
                      </span>
                    </div>
                  </template>
                  <template #description>
                    <div class="item-description">
                      <span class="sort-info">排序值: {{ item.sort }}</span>
                      <span class="value-count">参数值: {{ item.child.length }}个</span>
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-tooltip title="编辑">
                    <edit-outlined class="action-icon edit-icon" @click.stop="showEditModal(item)" />
                  </a-tooltip>
                  <a-tooltip title="删除">
                    <delete-outlined class="action-icon delete-icon" @click.stop="handleDelete(item)" />
                  </a-tooltip>
                </template>
              </a-list-item>
            </template>
            <template #empty>
              <div class="empty-state">
                <inbox-outlined class="empty-icon" />
                <span class="empty-text">暂无参数项</span>
              </div>
            </template>
          </a-list>
        </div>

        <!-- 右侧参数值列表 -->
        <div class="parameter-value-list">
          <div class="value-list-header">
            <div class="header-content">
              <div class="header-left">
                <span class="header-title">参数值列表</span>
                <span v-if="selectedItem" class="header-subtitle">
                  {{ selectedItem.name }} 的参数值
                </span>
              </div>
              <a-button 
                type="primary" 
                @click="showAddValueModal" 
                :disabled="!selectedItem"
                class="add-value-button"
              >
                <template #icon><plus-outlined /></template>
                添加参数值
              </a-button>
            </div>
          </div>
          <a-list
            :data-source="selectedItem?.child || []"
            :loading="loading"
            item-layout="horizontal"
            class="custom-list"
          >
            <template #renderItem="{ item }">
              <a-list-item class="value-list-item">
                <a-list-item-meta>
                  <template #title>
                    <div class="value-item">
                      <span class="value-name">{{ item.value }}</span>
                      <span v-if="item.priceOffset !== 0" 
                        :class="['price-offset', item.priceOffset < 0 ? 'negative' : 'positive']"
                      >
                        {{ item.priceOffset > 0 ? '+' : '' }}{{ item.priceOffset }}元
                      </span>
                    </div>
                  </template>
                  <template #description>
                    <div class="value-description">
                      <span class="stock-info">库存: {{ item.stock || 0 }}</span>
                    </div>
                  </template>
                </a-list-item-meta>
                <template #actions>
                  <a-tooltip title="编辑">
                    <edit-outlined class="action-icon edit-icon" @click.stop="showEditValueModal(item)" />
                  </a-tooltip>
                  <a-tooltip title="删除">
                    <delete-outlined class="action-icon delete-icon" @click.stop="handleDeleteValue(item)" />
                  </a-tooltip>
                </template>
              </a-list-item>
            </template>
            <template #empty>
              <div class="empty-state">
                <inbox-outlined class="empty-icon" />
                <span class="empty-text">请选择左侧的参数项</span>
              </div>
            </template>
          </a-list>
        </div>
      </div>
    </a-card>

    <!-- 添加参数项弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="添加参数项"
      @ok="handleAdd"
      @cancel="handleCancel"
      class="custom-modal"
    >
      <a-form
        :model="addForm"
        :rules="rules"
        ref="addFormRef"
        layout="vertical"
      >
        <a-form-item label="参数名称" name="name">
          <a-input v-model:value="addForm.name" placeholder="请输入参数名称" />
        </a-form-item>
        <a-form-item label="参数类型" name="type">
          <a-radio-group v-model:value="addForm.type" class="custom-radio-group">
            <a-radio :value="0">单选</a-radio>
            <a-radio :value="1">多选</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否必选" name="isRequired">
          <a-radio-group v-model:value="addForm.isRequired" class="custom-radio-group">
            <a-radio :value="0">可选</a-radio>
            <a-radio :value="1">必选</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排序值" name="sort">
          <a-input-number v-model:value="addForm.sort" :min="0" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑参数项弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑参数项"
      @ok="handleEdit"
      @cancel="handleEditCancel"
      class="custom-modal"
    >
      <a-form
        :model="editForm"
        :rules="rules"
        ref="editFormRef"
        layout="vertical"
      >
        <a-form-item label="参数名称" name="name">
          <a-input v-model:value="editForm.name" placeholder="请输入参数名称" />
        </a-form-item>
        <a-form-item label="参数类型" name="type">
          <a-radio-group v-model:value="editForm.type" class="custom-radio-group">
            <a-radio :value="0">单选</a-radio>
            <a-radio :value="1">多选</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否必选" name="isRequired">
          <a-radio-group v-model:value="editForm.isRequired" class="custom-radio-group">
            <a-radio :value="0">可选</a-radio>
            <a-radio :value="1">必选</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排序值" name="sort">
          <a-input-number v-model:value="editForm.sort" :min="0" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加参数值弹窗 -->
    <a-modal
      v-model:visible="addValueModalVisible"
      title="添加参数值"
      @ok="handleAddValue"
      @cancel="handleAddValueCancel"
      class="custom-modal"
    >
      <a-form
        :model="addValueForm"
        :rules="valueRules"
        ref="addValueFormRef"
        layout="vertical"
      >
        <a-form-item label="参数值" name="value">
          <a-input v-model:value="addValueForm.value" placeholder="请输入参数值" />
        </a-form-item>
        <a-form-item label="价格偏移" name="priceOffset">
          <a-input-number 
            v-model:value="addValueForm.priceOffset" 
            :min="-999" 
            :max="999" 
            style="width: 100%"
            placeholder="请输入价格偏移值"
          />
        </a-form-item>
        <a-form-item label="库存" name="stock">
          <a-input-number 
            v-model:value="addValueForm.stock" 
            :min="0" 
            style="width: 100%"
            placeholder="请输入库存数量"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑参数值弹窗 -->
    <a-modal
      v-model:visible="editValueModalVisible"
      title="编辑参数值"
      @ok="handleEditValue"
      @cancel="handleEditValueCancel"
      class="custom-modal"
    >
      <a-form
        :model="editValueForm"
        :rules="valueRules"
        ref="editValueFormRef"
        layout="vertical"
      >
        <a-form-item label="参数值" name="value">
          <a-input v-model:value="editValueForm.value" placeholder="请输入参数值" />
        </a-form-item>
        <a-form-item label="价格偏移" name="priceOffset">
          <a-input-number 
            v-model:value="editValueForm.priceOffset" 
            :min="-999" 
            :max="999" 
            style="width: 100%"
            placeholder="请输入价格偏移值"
          />
        </a-form-item>
        <a-form-item label="库存" name="stock">
          <a-input-number 
            v-model:value="editValueForm.stock" 
            :min="0" 
            style="width: 100%"
            placeholder="请输入库存数量"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { listAllParamItemWithValue, addParamItem, delParamItem, modifyParamItem, addParamValue, modifyParamValue, delParamValue } from '@/api/param';
import { message, Modal } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';

interface ParamValue {
  id: number;
  paramItemId: number;
  value: string;
  priceOffset: number;
  stock: number | null;
}

interface ParamItem {
  id: number;
  name: string;
  type: number;
  isRequired: number;
  sort: number;
  child: ParamValue[];
}

const loading = ref(false);
const parameterItems = ref<ParamItem[]>([]);
const selectedItem = ref<ParamItem | null>(null);

// 添加参数项相关的状态
const addModalVisible = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = ref({
  name: '',
  type: 0,
  isRequired: 0,
  sort: 0
});

// 编辑参数项相关的状态
const editModalVisible = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = ref({
  id: 0,
  name: '',
  type: 0,
  isRequired: 0,
  sort: 0
});

// 添加参数值相关的状态
const addValueModalVisible = ref(false);
const addValueFormRef = ref<FormInstance>();
const addValueForm = ref({
  paramItemId: 0,
  value: '',
  priceOffset: 0,
  stock: 0
});

// 编辑参数值相关的状态
const editValueModalVisible = ref(false);
const editValueFormRef = ref<FormInstance>();
const editValueForm = ref({
  id: 0,
  paramItemId: 0,
  value: '',
  priceOffset: 0,
  stock: 0
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择参数类型', trigger: 'change' }],
  isRequired: [{ required: true, message: '请选择是否必选', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
};

// 参数值表单验证规则
const valueRules = {
  value: [{ required: true, message: '请输入参数值', trigger: 'blur' }],
  priceOffset: [{ required: true, message: '请输入价格偏移', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
};

// 加载参数数据
const loadParameterData = async () => {
  loading.value = true;
  try {
    const res = await listAllParamItemWithValue();
    if (res.data.code === 200) {
      parameterItems.value = res.data.data;
    } else {
      message.error(res.data.msg || '获取参数数据失败');
    }
  } catch (error) {
    console.error('加载参数数据失败:', error);
    message.error('加载参数数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理选择参数项
const handleSelectItem = (item: ParamItem) => {
  selectedItem.value = item;
};

// 显示添加弹窗
const showAddModal = () => {
  addModalVisible.value = true;
};

// 处理添加参数项
const handleAdd = () => {
  addFormRef.value?.validate().then(() => {
    addParamItem(addForm.value).then(res => {
      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        loadParameterData();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    }).catch(error => {
      console.error('添加参数项失败:', error);
      message.error('添加失败，请稍后重试');
    });
  });
};

// 关闭添加弹窗
const handleCancel = () => {
  addModalVisible.value = false;
  addFormRef.value?.resetFields();
};

// 显示编辑弹窗
const showEditModal = (item: ParamItem) => {
  editForm.value = {
    id: item.id,
    name: item.name,
    type: item.type,
    isRequired: item.isRequired,
    sort: item.sort
  };
  editModalVisible.value = true;
};

// 处理编辑参数项
const handleEdit = () => {
  editFormRef.value?.validate().then(() => {
    modifyParamItem(editForm.value).then(res => {
      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        loadParameterData();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    }).catch(error => {
      console.error('修改参数项失败:', error);
      message.error('修改失败，请稍后重试');
    });
  });
};

// 关闭编辑弹窗
const handleEditCancel = () => {
  editModalVisible.value = false;
  editFormRef.value?.resetFields();
};

// 处理删除参数项
const handleDelete = (item: ParamItem) => {
  Modal.confirm({
    title: '确认删除',
    content: `此操作会默认删除绑定的参数值，确定要删除参数项"${item.name}"吗？`,
    okText: '确认',
    cancelText: '取消',
    okButtonProps: { danger: true },
    onOk: async () => {
      try {
        const res = await delParamItem(item.id);
        if (res.data.code === 200) {
          message.success('删除成功');
          loadParameterData();
        } else {
          message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除参数项失败:', error);
        message.error('删除失败，请稍后重试');
      }
    },
  });
};

// 显示添加参数值弹窗
const showAddValueModal = () => {
  if (!selectedItem.value) return;
  addValueForm.value = {
    paramItemId: selectedItem.value.id,
    value: '',
    priceOffset: 0,
    stock: 0
  };
  addValueModalVisible.value = true;
};

// 处理添加参数值
const handleAddValue = () => {
  addValueFormRef.value?.validate().then(() => {
    addParamValue(addValueForm.value).then(async res => {
      if (res.data.code === 200) {
        message.success('添加成功');
        addValueModalVisible.value = false;
        await loadParameterData();
        if (selectedItem.value) {
          const updatedItem = parameterItems.value.find(item => item.id === selectedItem.value?.id);
          if (updatedItem) {
            selectedItem.value = updatedItem;
          }
        }
      } else {
        message.error(res.data.msg || '添加失败');
      }
    }).catch(error => {
      console.error('添加参数值失败:', error);
      message.error('添加失败，请稍后重试');
    });
  });
};

// 关闭添加参数值弹窗
const handleAddValueCancel = () => {
  addValueModalVisible.value = false;
  addValueFormRef.value?.resetFields();
};

// 显示编辑参数值弹窗
const showEditValueModal = (item: ParamValue) => {
  editValueForm.value = {
    id: item.id,
    paramItemId: item.paramItemId,
    value: item.value,
    priceOffset: item.priceOffset,
    stock: item.stock || 0
  };
  editValueModalVisible.value = true;
};

// 处理编辑参数值
const handleEditValue = () => {
  editValueFormRef.value?.validate().then(() => {
    modifyParamValue(editValueForm.value).then(async res => {
      if (res.data.code === 200) {
        message.success('修改成功');
        editValueModalVisible.value = false;
        await loadParameterData();
        if (selectedItem.value) {
          const updatedItem = parameterItems.value.find(item => item.id === selectedItem.value?.id);
          if (updatedItem) {
            selectedItem.value = updatedItem;
          }
        }
      } else {
        message.error(res.data.msg || '修改失败');
      }
    }).catch(error => {
      console.error('修改参数值失败:', error);
      message.error('修改失败，请稍后重试');
    });
  });
};

// 关闭编辑参数值弹窗
const handleEditValueCancel = () => {
  editValueModalVisible.value = false;
  editValueFormRef.value?.resetFields();
};

// 处理删除参数值
const handleDeleteValue = (item: ParamValue) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除参数值"${item.value}"吗？`,
    okText: '确认',
    cancelText: '取消',
    okButtonProps: { danger: true },
    onOk: async () => {
      try {
        const res = await delParamValue(item.id);
        if (res.data.code === 200) {
          message.success('删除成功');
          await loadParameterData();
          if (selectedItem.value) {
            const updatedItem = parameterItems.value.find(item => item.id === selectedItem.value?.id);
            if (updatedItem) {
              selectedItem.value = updatedItem;
            }
          }
        } else {
          message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除参数值失败:', error);
        message.error('删除失败，请稍后重试');
      }
    },
  });
};

onMounted(() => {
  loadParameterData();
});
</script>

<style scoped>
.parameter-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.page-header {
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.page-description {
  font-size: 14px;
  color: #666;
}

.parameter-content {
  display: flex;
  gap: 24px;
  height: calc(100vh - 200px);
}

.parameter-list {
  flex: 3;
  border-right: 1px solid #f0f0f0;
  padding-right: 24px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.parameter-value-list {
  flex: 7;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.list-header, .value-list-header {
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.header-count {
  font-size: 14px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.header-subtitle {
  font-size: 14px;
  color: #666;
  margin-left: 8px;
}

.custom-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 8px;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

.item-tags {
  display: flex;
  gap: 8px;
}

.type-tag, .required-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 22px;
  line-height: 20px;
  border-radius: 11px;
}

.item-description {
  display: flex;
  gap: 16px;
  margin-top: 4px;
  color: #666;
  font-size: 13px;
}

.value-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.value-name {
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

.price-offset {
  font-size: 13px;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #f5f5f5;
}

.price-offset.positive {
  color: #ff4d4f;
}

.price-offset.negative {
  color: #52c41a;
}

.value-description {
  margin-top: 4px;
  color: #666;
  font-size: 13px;
}

.selected-item {
  background-color: #e6f7ff;
  border-radius: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-text {
  font-size: 14px;
}

.action-icon {
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-icon {
  color: #1890ff;
}

.delete-icon {
  color: #ff4d4f;
}

.action-icon:hover {
  transform: scale(1.1);
}

:deep(.ant-list-item) {
  padding: 16px;
  border-radius: 8px;
  transition: all 0.3s;
  margin-bottom: 8px;
}

:deep(.ant-list-item:hover) {
  background-color: #f5f5f5;
}

:deep(.selected-item:hover) {
  background-color: #e6f7ff;
}

:deep(.ant-list-item-actions) {
  display: flex;
  gap: 16px;
}

:deep(.ant-list-item-actions > li) {
  margin: 0;
}

:deep(.ant-modal-content) {
  border-radius: 8px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-radio-group) {
  display: flex;
  gap: 24px;
}

.add-button, .add-value-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .parameter-content {
    flex-direction: column;
  }
  
  .parameter-list {
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
    padding-right: 0;
    padding-bottom: 24px;
  }
  
  .parameter-value-list {
    padding-top: 24px;
  }
}
</style>
